package com.fhao.common.core.utils;

import com.fhao.common.core.constants.JwtConstants;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.HashMap;
import java.util.Map;

public class JwtUtils {
    /** * 生成令牌
     * @ @param claims 数据
     * @ @param secret 密钥
     * @ @return 令牌
     */
    public static String createToken(Map<String,Object> claims,String secret) {
        String token = Jwts.builder().setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
        return token;
    }

    /**
     * 从令牌中获取数据
     * @param token 令牌
     * @param secret 密钥
     * @return 数据
     */
    public static Claims parseToken(String token,String secret) {
        return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
    }

    public static String getUserKey(Claims claims) {
        Object userKey =  claims.get(JwtConstants.LOGIN_USER_KEY);
        return toStr(userKey);
    }

    private static String toStr(Object value) {
        if(value == null) {
            return "";
        }
        return value.toString();
    }

    public static String getUserId(Claims claims) {
        Object userId = claims.get(JwtConstants.LOGIN_USER_ID);
        return toStr(userId);
    }

//    public static void main(String[] args) {
////        Map<String,Object> claims = new HashMap<>();
////        claims.put("userId",123456l);
////        //sercret 保密 随机 不能硬编码 需要定时更换
////        System.out.println(createToken(claims,"zjuuhjnmiij"));
//        String token = "eyJhbGciOiJIUzUxMiJ9.eyJ1c2VySWQiOjEyMzQ1Nn0.8j6syjb5G4RnwmVpedyYVJ12oTR62UEp5vd5ZjMLvvLCzKEGQLz7FpZCL1IaH0-xX3sEaFAxhs7vvByTpsecAQ";
//        Claims claims = parseToken(token, "zjuuhj6846d5fasd/*adf80=-@%nmiij");
//        System.out.println(claims);
//    }
}
